package com.reactor.handler;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.mina.common.IoSession;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

public class EventDecoupler{
 private final static String COMMAND_NAME_ATTRIBUTE = "name";
	public EventDecoupler(IoSession sessionForResponse, String request) {
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		try {

			//Using factory get an instance of document builder
			DocumentBuilder db = dbf.newDocumentBuilder();

			//parse using builder to get DOM representation of the XML file
			//Document dom = db.parse("reqCommand.xml");
			InputStream istream = new ByteArrayInputStream(request.getBytes("UTF-8"));
			Document dom = db.parse(istream);
			System.out.println(dom.toString());
			Element docEle = dom.getDocumentElement();
			System.out.println(docEle.getNodeName());
			NodeList nl = docEle.getElementsByTagName("command");
			if(nl != null && nl.getLength() > 0) {
				for(int i = 0 ; i < nl.getLength();i++) {

					//get the employee element
					Element el = (Element)nl.item(i);
					ICommand command = this.getCommand(el);
					ICommandResult result = command.execute();
					if (result.isResultExist())
					{
						String strForResult = result.getResult();
						sessionForResponse.write(strForResult);
					}
				}
			}



		}catch(ParserConfigurationException pce) {
			pce.printStackTrace();
		}catch(SAXException se) {
			se.printStackTrace();
		}catch(IOException ioe) {
			ioe.printStackTrace();
		}

	}
	
	/**
	 * I take an employee element and read the values in, create
	 * an Employee object and return it
	 */
	private ICommand getCommand(Element command) {
		String commandName =command.getAttribute(EventDecoupler.COMMAND_NAME_ATTRIBUTE);
		return CommandFactory.getInstance().createCommand(commandName,
													command);
		
		//for each <employee> element get text or int values of
		//name ,id, age and name
		//String name = getTextValue(empEl,"Name");
		//int id = getIntValue(empEl,"Id");
		//int age = getIntValue(empEl,"Age");

		//String type = empEl.getAttribute("type");

		//Create a new Employee with the value read from the xml nodes
		//Employee e = new Employee(name,id,age,type);
	}




}
